package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.config.RentApi;
import com.ybkj.daijia.server.model.RentShop;
import com.ybkj.daijia.server.service.RentShopService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DefaultRentShopService implements RentShopService {

    @Autowired
    private RentApi rentApi;

    @Autowired
    private SettingUtils settingUtils;

    @Override
    public List<RentShop> exportRentShop(Long companyId, String shopName) {

        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(rentApi.EXPORT_RENTSHOP)
            .append("?appkey={appkey}");

        Map<String, String> kv = new HashMap<String, String>();
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }

        if (shopName != null) {
            kv.put("shopName", String.valueOf(shopName));
            builder.append("&shopName={shopName}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<Map<String, String>> shopList = new ArrayList<Map<String, String>>();
        shopList.add(kv);

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().create();
                List<RentShop> rentShops = gson
                    .fromJson(data.toString(), new TypeToken<List<RentShop>>() {
                    }.getType());

                return rentShops;
            }
        }
        return null;
    }

}
